package com.shanghai.market.plshnaghai;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.util.Base64;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.MemoryCache;
import com.nostra13.universalimageloader.cache.memory.impl.LRULimitedMemoryCache;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.shanghai.market.plshnaghai.constants.constant;
import com.shanghai.market.plshnaghai.entity.AppData;
import com.shanghai.market.plshnaghai.net.RequestManager;
import com.shanghai.market.plshnaghai.net.VolleyParams;
import com.shanghai.market.plshnaghai.utils.Utils;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * Created by Administrator on 2017/8/15.
 */

public class AppApplication extends Application {

    private static AppApplication instance;

    private SharedPreferences preferences;


    @Override
    public void onCreate() {
        super.onCreate();
        initData();
        RequestManager.init(this);
        initImageLoader(this);

        instance = this;
    }

    private void initData() {
        preferences = getSharedPreferences(constant.Config.LOGIN_STATUS, Activity.MODE_PRIVATE);
    }

    public static AppApplication getInstance() {
        return instance;
    }


    /**
     * 检测网络是否连接
     *
     * @return true:已连接；false:未连接
     */
    public boolean isNetConnected() {
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
        if (activeInfo == null || !activeInfo.isConnected()) {
            return false;
        }
        return true;
    }

    /**
     * 获取应用版本号
     *
     * @return 应用版本号
     */
    public String getVersionName() {
        PackageManager packageManager = getPackageManager();
        PackageInfo packInfo = null;
        String version = null;
        try {
            packInfo = packageManager.getPackageInfo(getPackageName(), 0);
            version = packInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return version;
    }

    /**
     * 初始化网络请求头部
     *
     * @return
     */
    public VolleyParams initHttpHeader() {
        final VolleyParams headers = new VolleyParams();
        final AppData data = getAppData();
        final String sig = data.getSig();
        final String d_type = data.getD_type();
        final String token = data.getToken();
        final String cookie = data.getCookie();
//        headers.put("sig", sig());
//        headers.put("d_type", "2");
        headers.put("Authorization", authorization());

        return headers;
    }

    public String sig() {
        String appId = "54058d6832cbc";
        String appSecrect = "992495c48449db262cdbc1241c7484fe";
        String time = Utils.getTime();
        String str = Utils.MD5(appId + appSecrect + time);
        String httpStr = "d_type=2" + "&sig=" + str;
        return httpStr;

    }

    public String authorization() {
        String appId = "54058d6832cbc";
        String time = Utils.getTime();
        String ton = appId + ":" + time;
        String str = Base64.encodeToString(ton.getBytes(), Base64.DEFAULT);
        return str;
    }

    /**
     * 获取设备号ID
     *
     * @return
     */
    public String getDevicesSN() {
        String deviceSN = null;
        final TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String deviceId = tm.getDeviceId();
        if (null == deviceId) {// 如果获取的 设备ID 为空，则取mad地址
            String macAdress = null;
            Enumeration<NetworkInterface> enumerations;
            try {
                enumerations = NetworkInterface.getNetworkInterfaces();
                while (enumerations.hasMoreElements()) {
                    NetworkInterface networkInterface = (NetworkInterface) enumerations.nextElement();
                    if (null != networkInterface.getHardwareAddress()) {
                        macAdress = Base64.encodeToString(networkInterface.getHardwareAddress(), Base64.DEFAULT);
                        break;
                    }
                }
            } catch (SocketException e) {
                WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                WifiInfo info = wifi.getConnectionInfo();
                macAdress = info.getMacAddress();
            }
            deviceSN = macAdress;
        } else {
            deviceSN = deviceId;
        }
        deviceSN = deviceSN == null ? "example" : deviceSN;// 保证其不为空
        return deviceSN;
    }

    public void saveAppData(AppData data) {
        final SharedPreferences.Editor editor = preferences.edit();
        editor.putString(constant.Config.TOKEN, data.getToken());
        editor.putBoolean(constant.Config.IS_LOGIN, data.isLogin());
        editor.putString(constant.Config.COOKIE, data.getCookie());
        editor.putInt(constant.Config.USER_ID, data.getUserId());
        editor.putString(constant.Config.PHONE_NO, data.getPhone());
        editor.commit();
    }

    public AppData getAppData() {
        final AppData data = new AppData();
        final int userId = preferences.getInt(constant.Config.USER_ID, 0);
        final String token = preferences.getString(constant.Config.TOKEN, "");
        final String cookie = preferences.getString(constant.Config.COOKIE, "");
        final boolean isLogin = preferences.getBoolean(constant.Config.IS_LOGIN, false);
        final String phone = preferences.getString(constant.Config.PHONE_NO, "");
        data.setCookie(cookie);
        data.setUserId(userId);
        data.setToken(token);
        data.setLogin(isLogin);
        data.setPhone(phone);
        return data;
    }


    private void initImageLoader(Context context) {
        int memoryCacheSize = (int) (Runtime.getRuntime().maxMemory() / 8);

        MemoryCache memoryCache;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            memoryCache = new LruMemoryCache(memoryCacheSize);
        } else {
            memoryCache = new LRULimitedMemoryCache(memoryCacheSize);
        }

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                .threadPriority(Thread.NORM_PRIORITY - 2).memoryCache(memoryCache).denyCacheImageMultipleSizesInMemory()
                .diskCacheFileNameGenerator(new Md5FileNameGenerator()).tasksProcessingOrder(QueueProcessingType.LIFO)
                .build();
        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config);
    }

}
